package com.starbaba.core.utils.io;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

/**
 * 本地文件IO工具类
 *
 * @Copyright: Copyright (c) 2006
 * @Company: Revenco Tech Ltd.
 * @anthor chenminhui<chenminhui@revenco.com>
 * @since 2011-12-30 下午10:53:12
 * @version V1.0
 */
public class FileIOUtil extends BaseIOUtil {
	
	/**
	 * 生成目标目录结构
	 * 
	 * @param urlDir 目标目录
	 * @throws IOException
	 *
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor chenminhui<chenminhui@revenco.com>
	 * @since 2011-12-31 上午12:27:09
	 * @version V1.0
	 */
	public static void mkdirs(String urlDir) throws IOException {
		
		if(StringUtils.startsWithIgnoreCase(urlDir, IOUtilFactory.PROTOCOL_FILE)) {
			urlDir = StringUtils.substring(urlDir, StringUtils.length(IOUtilFactory.PROTOCOL_FILE));
		}
		
		FileUtils.forceMkdir(new File(urlDir));
	}
	
	/**
	 * 打开本地目标文件，若目标文件父目录不存在，则创建，最后打开目标文件输出流
	 * 
	 * @param urlSavePath 本地目标文件目录
	 * @param filename 目标文件名
	 * @return OutputStream 目标文件输出流
	 * @throws Exception
	 *
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor chenminhui<chenminhui@revenco.com>
	 * @since 2011-12-31 上午12:27:41
	 * @version V1.0
	 */
	@Override
	public OutputStream openOutputStream(String urlSavePath, String filename) throws Exception {
		mkdirs(urlSavePath);
		
		return FileUtils.openOutputStream(new File(urlSavePath, filename));
	}
	
	/**
	 * 打开本地目标文件输入流
	 * 
	 * @param urlFilePath 本地目标文件
	 * @return InputStream 目标文件输入流
	 * @throws IOException
	 *
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor chenminhui<chenminhui@revenco.com>
	 * @since 2011-12-31 上午12:27:43
	 * @version V1.0
	 */
	@Override
	public InputStream openInputStream(String urlFilePath) throws IOException {
		if(StringUtils.startsWithIgnoreCase(urlFilePath, IOUtilFactory.PROTOCOL_FILE)) {
			urlFilePath = StringUtils.substring(urlFilePath, StringUtils.length(IOUtilFactory.PROTOCOL_FILE));
		}
		
		return FileUtils.openInputStream(new File(urlFilePath));
	}
}
